package com.qinyu.treehole.service.Impl;

import com.qinyu.treehole.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

@Service
public class EmailServiceImpl implements EmailService {

    // Spring官方提供的集成邮件服务的实现类，目前是Java后端发送邮件和集成邮件服务的主流工具。
    @Autowired
    private JavaMailSender mailSender;
    @Value("${spring.mail.username}")
    private String fromEmail;
    @Value("${host}")
    private String host;
    /**
     * 发送文本邮件
     *
     * @param to      收件人
     * @param subject 标题
     * @param content 正文
     */
    public void sendSimpleMail(String to, String subject, String content) {
        SimpleMailMessage message = new SimpleMailMessage();

        message.setFrom(fromEmail); // 发件人
        message.setTo(to);
        message.setSubject(subject);
        message.setText(content);

        mailSender.send(message);
    }

    @Override
    public void sendHtmlMail(String to, String subject, String centent) throws MessagingException {
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
        helper.setFrom(fromEmail);
        helper.setTo(to);
        helper.setSubject(subject);
        helper.setText(centent, true);
        mailSender.send(mimeMessage);
    }

    @Override
    public boolean sendActiveHtmlMail(String to, String code) {
        String top = "您好！这里是\"轻语\"树洞: 点击以下链接激活您的账号(有效时间5分钟)：<br/>";
        String bottom = "<ul><li>本邮件为自动发送，请勿直接回复本邮件</li><li>如果您未登录本网站，请忽视这条邮件</li></ul>";
        String mid = host + "/#/register?code=" + code;
        try {
            sendHtmlMail(to,"\"轻语\"树洞", top + "<a href=\""+ mid + "\">"+ mid +"</a>" + bottom);
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

}
